const { Builder, By, until } = require('selenium-webdriver');
const sharp = require('sharp');
const fs = require('fs');
const { get_code } = require('./cy');  // 假设 get_code 在 cy.js 文件中有定义
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

async function startProcess() {
  rl.question('输入start以开启进程: ', async (sign) => {
    if (sign === 'start') {
      await enterHueb();
    } else {
      rl.close();
    }
  });
}

async function enterHueb() {
  let driver = await new Builder().forBrowser('MicrosoftEdge').build();
  try {
    await driver.get('https://cas-443.webvpn.hueb.edu.cn/cas/login?service=https%3A%2F%2Fwebvpn.hueb.edu.cn%2Fusers%2Fauth%2Fcas%2Fcallback%3Furl%3Dhttps%253A%252F%252Fwww.hueb.edu.cn%252F');

    let hueb_id = '202222450619';
    let hueb_password = 'hxg20021126';

    let user_input = await driver.findElement(By.id('username'));
    let password_input = await driver.findElement(By.id('password'));
    let code_input = await driver.findElement(By.id('captcha'));
    user_input.sendKeys(hueb_id);
    password_input.sendKeys(hueb_password);

    let code_img = await driver.findElement(By.id('captchaImg'));
    await driver.takeScreenshot().then(
      function (image, err) {
        fs.writeFileSync('aa.png', image, 'base64');
      }
    );

    let size = await code_img.getRect();
    let area = { left: 534, top: 487, width: size.width, height: size.height };

    await sharp('aa.png')
      .extract(area)
      .toFile('code.png', async (err, info) => {
        if (err) throw err;

        let code = await get_code('code.png', '1004').pic_str;
        await code_input.sendKeys(code);

        let login_button = await driver.findElement(By.id('login_submit'));
        await login_button.click();

        console.log('成功登录鸡毛！！');
        await huebToRuige(driver);
      });
  } finally {
    // rl.close(); // Uncomment if you want to close readline interface
    // await driver.quit(); // Uncomment if you want to close the browser after the task is complete
  }
}

async function huebToRuige(driver) {
  let ruige_into = await driver.findElement(By.xpath('/html/body/div[5]/div/ul/li[18]'));
  await ruige_into.click();
  await driver.sleep(5000);

  let num = await driver.getAllWindowHandles();
  await driver.switchTo().window(num[num.length - 1]);
  console.log('已跳转至锐格登录页');
  await enterRuige(driver);
}

async function enterRuige(driver) {
  let hueb_id = '202222450619';
  let ruige_password = 'hxg20021126';

  let ruigeuser_input = await driver.findElement(By.id('loginMail'));
  let ruigepswd_input = await driver.findElement(By.id('loginPass'));
  let ruigecode_input = await driver.findElement(By.id('authcode'));
  await ruigeuser_input.sendKeys(hueb_id);
  await ruigepswd_input.sendKeys(ruige_password);

  await driver.takeScreenshot().then(
    function (image, err) {
      fs.writeFileSync('bb.png', image, 'base64');
    }
  );

  let ruigerangle = { left: 1035, top: 542, width: 134, height: 46 };
  await sharp('bb.png')
    .extract(ruigerangle)
    .toFile('ruigecode.png', async (err, info) => {
      if (err) throw err;

      let ruigecode = await get_code('ruigecode.png', '4004').pic_str;
      await ruigecode_input.sendKeys(ruigecode);

      let ruigelog_button = await driver.findElement(By.id('loginSubmit'));
      await ruigelog_button.click();
      await driver.sleep(3000);

      console.log('成功登录锐格！');
      // await findTopic(driver); // Uncomment if you want to call findTopic
    });
}

async function findTopic(driver) {
  fs.readFile('./text.txt', 'utf8', async (err, data) => {
    if (err) throw err;
    let content = data.split('·');

    let class_into = await driver.findElement(By.xpath('//div[@id="outter"]/div[2]/div[2]/div[3]/div/table/tbody/tr/td[1]'));
    await class_into.click();

    let prac_into = await driver.findElement(By.xpath('//*[@id="outter"]/div[1]/div/div[2]/ul/li[3]'));
    await prac_into.click();
    await driver.sleep(1000);

    let swich1 = await driver.findElement(By.id('treeDemo_1_switch'));
    await swich1.click();
    await driver.sleep(1000);

    let swich2 = await driver.findElement(By.id('treeDemo_7_switch'));
    await swich2.click();
    await driver.sleep(1000);

    let swich3 = await driver.findElement(By.id('treeDemo_9_switch'));
    await swich3.click();
    await driver.sleep(1000);

    for (let i = 43; i < 53; i++) {
      let swich4 = await driver.findElement(By.id(`treeDemo_${i}_a`));
      await swich4.click();
      await driver.sleep(1000);

      let inputspace = await driver.findElement(By.id('myCoder_1'));
      await inputspace.clear();

      let con = content[58 - i - 5];
      con = con.replace('"#', '#').replace('}"', '}').replace('""', '"');

      await inputspace.sendKeys(con);

      let submit_btn = await driver.findElement(By.id('exerSubBtn2'));
      await submit_btn.click();
      await driver.sleep(3000);
    }
  });
}

startProcess();
